package com.huping.controller;

import com.alibaba.fastjson.JSONObject;
import com.huping.pojo.Result;
import com.huping.pojo.Student;
import com.huping.pojo.Teacher;
import com.huping.pojo.User;
import com.huping.service.BasicService;
import com.huping.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class BasicController {

    @Autowired
    private BasicService userService;

    @PostMapping("/basic/login")
    public Result login(@RequestBody User user){
        log.info("用户登录:{}",user);
        User u = userService.login(user);

        //登陆成功生成token
        if(u!=null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("userid",user.getUserid());
            claims.put("password",user.getPassword());
            claims.put("kind",u.getKind());
            String jwt = JwtUtils.generateJwt(claims);
            Map<String,String> m = new HashMap<String , String>();
            m.put("token",jwt);
            m.put("kind",u.getKind());
            return Result.success(m);
        }

        //登陆失败
        return Result.error("用户名或密码错误");
    }

    @PostMapping("/basic/register")
    public Result register(@RequestBody JSONObject param){
        log.info("用户注册:{}",param.getString("userid"));
        if(param.getString("kind").equals("student")) param.put("kind","1");
        if(param.getString("kind").equals("teacher")) param.put("kind","2");

        return userService.register(param);
    }


    @GetMapping("/basic/getInformation")
    public Result  getInformation( @RequestHeader String token){

        Claims claims=JwtUtils.parseJWT(token);
        String userid= (String) claims.get("userid");
        String kind=(String)  claims.get("kind");
         log.info("用户获取信息:{}",userid);
        return userService.getInformation(userid,kind);


    }

    @PostMapping("/basic/modification")
    public Result  modification(@RequestBody JSONObject param, @RequestHeader String token){

        Claims claims=JwtUtils.parseJWT(token);
        String userid= (String) claims.get("userid");
        String kind=(String) claims.get("kind");
        log.info("用户修改信息:{}",userid);
          return userService.modification( param, userid,kind);

    }
    @PostMapping("/basic/modifyPassword")
    public Result  modifyPassword(@RequestBody JSONObject param, @RequestHeader String token){

        Claims claims=JwtUtils.parseJWT(token);
        String userid= (String) claims.get("userid");

        log.info("用户修改密码:{}",userid);
        return userService.modifyPassword( param, userid);

    }




}
